#include "xmlScribe.h"

xmlScribe::xmlScribe()
		:QObject()
{
	qDebug() << "Info : start xmlScribe...";
	//connect(this, SIGNAL(StatusAutoUpdate(bool, QString, QString, QString)), this, SLOT(Debug_StatusAutoUpdate(bool, QString, QString, QString)));
	//connect(this, SIGNAL(TasktoAddFileIntoTree(QString, QString, QString, int)), this, SLOT(Debug_StatusNewFile(QString, QString, QString, int)));
}

xmlScribe::~xmlScribe()
{
	qDebug() << "Info :  stop xmlScribe...";
}

void xmlScribe::Set_Path_Updater(QString NewVal)
{
	Path_Updater = NewVal;
}

void xmlScribe::ReadFile(QString PathToRead)
{
	QFile file(PathToRead);
	if (!file.open(QFile::ReadOnly | QFile::Text)) 
	{
		QMessageBox::warning(0, QObject::trUtf8("R file"),
						QObject::trUtf8("Cannot read file %1:\n%2.")
						.arg(PathToRead)
						.arg(file.errorString()));
		return;
	}
	read(&file);
}

bool xmlScribe::read(QIODevice *device)
{
    QString errorStr;
    int errorLine;
    int errorColumn;

    if (!domDocument.setContent(device, true, &errorStr, &errorLine, &errorColumn)) 
	{
        QMessageBox::information(0, QObject::trUtf8("DOM Bookmarks"),
                                QObject::trUtf8("Parse error at line %1, column %2:\n%3")
                                .arg(errorLine)
                                .arg(errorColumn)
                                .arg(errorStr));
        return false;
    }

    QDomElement root = domDocument.documentElement();
    if (root.tagName() != "updateslist") 
	{
        QMessageBox::information(0, QObject::trUtf8("Updates list"),
                                  QObject::trUtf8("La liste de mise à jour n'est pas valide."));
        return false;
    }

    QDomElement Mechild = root.firstChildElement("updater");
    while (!Mechild.isNull()) 
	{
		parseMeElement(Mechild);
		Mechild = Mechild.nextSiblingElement("updater");
    }
	QDomElement Fileschild = root.firstChildElement("allfiles");
    while (!Fileschild.isNull()) 
	{
		QDomElement child = Fileschild.firstChildElement();
		while (!child.isNull()) 
		{
			if (child.tagName() == "file") 
			{
				parseFileElement(child);
			}
			child = child.nextSiblingElement();
		}		
		Fileschild = Fileschild.nextSiblingElement("othersfiles");
    }
    return true;
}

void xmlScribe::parseMeElement(const QDomElement &element)
{
	//Var to return
	bool autoUpdate = false;
	QString ThisSha1 = "";
	QString NewFileName = "";
	QString NewPathName = "";
	
	//Set autoupdate
	QString Str_autoupdate = element.firstChildElement("autoupdate").text();
    if (!Str_autoupdate.isEmpty())
	{
		if(Str_autoupdate == "enabled")
		{autoUpdate = true;}	
	}
	if(autoUpdate)
	{
		ThisSha1 = element.firstChildElement("sha1").text();
		NewFileName = element.firstChildElement("newFileName").text();
		NewPathName = element.firstChildElement("newPath").text();
	}
	emit StatusAutoUpdate(autoUpdate, ThisSha1, NewPathName, NewFileName);
}
void xmlScribe::parseFileElement(const QDomElement &element)
{
	//Var to return
	QString FileSha1 = "";
	QString FileName = "";
	QString PathName = "";
	int priority = 0;
	
	FileName = element.firstChildElement("filename").text();
	PathName = element.firstChildElement("path").text();
	FileSha1 = element.firstChildElement("sha1").text();
	priority = (element.firstChildElement("priority").text()).toInt();
	
	emit TasktoAddFileIntoTree(FileSha1, PathName, FileName, priority);
}
int xmlScribe::WriteFile(QList<UpdateFile*> ListXML, QString PathToWrite)
{
	qDebug() << "Info : Generate XML file";
	QFile file;
	const int IndentSize = 4;//taille de tab
	QDomDocument domUpdatesList;
	int i =0;
	file.setFileName(PathToWrite);
	//Création du path XML
	QDir TstDir;
	QFileInfo TmpFileInfo(file);
	TstDir.setPath(TmpFileInfo.absolutePath());
	if(!TstDir.exists())
	{//créer dossier
		#ifdef QT_DEBUG
			qDebug() << "Warning : Folder" << TstDir.path() << "dont exist!";
		#endif
		if(!TstDir.mkpath(TstDir.path()))
		{	
			qDebug() << "Error : Failled to create path :" << TstDir.path();
			return 1;
			//TODO Gèrer l'exeption
		}
	}
	//Création de la structure 1er niveau
	QDomElement Root = domUpdatesList.createElement("updateslist"); //je créé la racine
	Root.setAttribute("version","1.0");
	QDomElement SelfUpdate = domUpdatesList.createElement("updater");
	QDomElement Files = domUpdatesList.createElement("allfiles");
	Root.appendChild(SelfUpdate);
	Root.appendChild(Files);
	domUpdatesList.appendChild(Root);

	//Génération des informations de l'updater
	QDomElement Self_autoupdate = domUpdatesList.createElement("autoupdate");
	Self_autoupdate.appendChild(domUpdatesList.createTextNode("disabled")); // J'insère son contenu
	QDomElement Self_sha1 = domUpdatesList.createElement("sha1");
	Self_sha1.appendChild(domUpdatesList.createTextNode("001"));
	QDomElement Self_newFileName = domUpdatesList.createElement("newFileName");
	Self_newFileName.appendChild(domUpdatesList.createTextNode("ici/etla"));
	QDomElement Self_newPath = domUpdatesList.createElement("newPath");
	Self_newPath.appendChild(domUpdatesList.createTextNode("monbônom"));
	SelfUpdate.appendChild(Self_autoupdate);
	SelfUpdate.appendChild(Self_sha1);
	SelfUpdate.appendChild(Self_newFileName);
	SelfUpdate.appendChild(Self_newPath);

	QDomElement *fileToUp;
	QDomElement *file_filename;
	QDomElement *file_path;
	QDomElement *file_sha1;
	QDomElement *file_priority;
	QString FileNameToRemovePath;
	for(i=0;i<ListXML.size();i++)
	{
		fileToUp = new QDomElement(domUpdatesList.createElement("file"));
			file_filename = new QDomElement(domUpdatesList.createElement("filename"));
			file_filename->appendChild(domUpdatesList.createTextNode(ListXML[i]->getFilename()));
			file_path = new QDomElement(domUpdatesList.createElement("path"));
			FileNameToRemovePath = ListXML[i]->getPath();
				if(FileNameToRemovePath.contains(Path_Updater) and !Path_Updater.isEmpty())
				{FileNameToRemovePath = FileNameToRemovePath.remove(Path_Updater);}
				else
				{/*TODO : à traiter : fichier hors du path!*/}
			file_path->appendChild(domUpdatesList.createTextNode(FileNameToRemovePath));
			file_sha1 = new QDomElement(domUpdatesList.createElement("sha1"));
			file_sha1->appendChild(domUpdatesList.createTextNode(ListXML[i]->getSha1()));
			file_priority = new QDomElement(domUpdatesList.createElement("priority"));
			file_priority->appendChild(domUpdatesList.createTextNode(QString::number(ListXML[i]->getpriority())));
		
		
		fileToUp->appendChild(*file_filename);
		fileToUp->appendChild(*file_path);
		fileToUp->appendChild(*file_sha1);
		fileToUp->appendChild(*file_priority);
		Files.appendChild(*fileToUp);
	}
	if (!file.open(QFile::WriteOnly | QFile::Text))
	{
		qWarning() << "Error : Unable to write XML file";
		return 1;
	}
	else
	{
		QTextStream out(&file);
		domUpdatesList.save(out, IndentSize);
		file.close();
		qDebug() << "Info : XML written!";
		return 0;
	}
	
}

void xmlScribe::Debug_StatusAutoUpdate(bool AutoUpdateEnabled, QString NewSha1, QString NewPath, QString NewFileName)
{
	#ifdef ENABLE_DEBUG_STATUSAUTOUPDATE
		QString tmp_strEnabled = "Disabled";
		if(AutoUpdateEnabled){tmp_strEnabled = "Enabled";}
		qDebug() << "DEBUG == New config : AutoUpdate = " << tmp_strEnabled << "| Sha1 =" << NewSha1 << "| Path =" << NewPath << "| Name =" << NewFileName; 
	#endif
}
void xmlScribe::Debug_StatusNewFile(QString Sha1, QString Path, QString FileName, int priority)
{
	#ifdef ENABLE_DEBUG_STATUSNEWFILE
		qDebug() << "DEBUG == New file : Name = " << FileName  << "| Path =" << Path << "| Sha1 =" << Sha1 << "| prio =" << QString::number(priority); 
	#endif
}
